//
//  QuestionViewController.m
//  inquiry
//
//  Created by 高宇 on 2020/5/23.
//  Copyright © 2020 高宇. All rights reserved.
//
#define SCREEN_WIDTH  ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)

#define kWeakSelf(type) __weak typeof(type) weak##type = type;
#define kStrongSelf(type) __strong typeof(type) type = weak##type;

#import "QuestionViewController.h"
#import "RadioCollectionViewCell.h"
#import "BlankCell.h"
#import "GXToast.h"
#import "ULNetHelper.h"
#import "Interface.h"
#import "NSString+MD5.h"
#import "FinishViewController.h"
#import "JsonObject.h"

@interface QuestionViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) NSMutableArray *arr;  //总数据
@property (copy, nonatomic) NSString *topTopicIndex;  //上一页面对应topicIndex
@end

static NSString * const reuseIdentifier = @"Cell";
static NSString * const blankCell = @"BlankCell";

@implementation QuestionViewController

//在页面出现的时候就将黑线隐藏起来
 -(void)viewWillAppear:(BOOL)animated
{
    //显示导航栏下面的线条
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
        
    //初始化数组
    self.arr = [NSMutableArray array];
    
    [self createUI];
    [self getData];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0, 40, 30);
    [backButton setTitle:@" 返回" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor colorWithRed:173/255.0 green:173/255.0 blue:189/255.0 alpha:1.0] forState:0];
    [backButton setImage:[[UIImage imageNamed:@"fanhui"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];

    [backButton addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}

- (void)backClick:(id)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)getData{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"questionnaireId"] = self.questionnaireId;
    dic[@"userId"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"];
    
    [ULNetHelper POST:queryDetailPath parameters:dic success:^(id responseObject) {
        NSDictionary *dic = responseObject;
        long code = [dic[@"code"] longValue];
        if (code == 200) {
            NSString *title = responseObject[@"data"][@"title"];
            self.title = title;
            
            self.arr = [NSMutableArray arrayWithArray:responseObject[@"data"][@"data"]];
            [self.collectionView reloadData];
            
        }else{
            NSString *msg = responseObject[@"msg"];
            [GXToast showText:msg];
        }
    }];
}

- (BOOL)isPhoneX {
    BOOL iPhoneX = NO;
    if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {//判断是否是手机
        return iPhoneX;
    }
    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[UIApplication sharedApplication] keyWindow];
        if (mainWindow.safeAreaInsets.bottom > 0.0) {
            iPhoneX = YES;
        }
    }
    return iPhoneX;
}

- (void)createUI{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-44);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    self.collectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44);
    if ([self isPhoneX]) {  //判断刘海屏
        layout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-44-24-34);
        self.collectionView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-44-24-34);
    }
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.backgroundColor  = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.scrollEnabled = NO;
    
    if (@available(iOS 10.0,*)) {
       self.collectionView.prefetchingEnabled = NO;
    }
    
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([RadioCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BlankCell class]) bundle:nil] forCellWithReuseIdentifier:blankCell];
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.arr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"index == %ld",(long)indexPath.row);
    if (indexPath.row+1 == self.arr.count) {
        UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
        [rightButton setTitle:@"交卷" forState:0];
        [rightButton setTitleColor:[UIColor whiteColor] forState:0];
        rightButton.backgroundColor = [UIColor colorWithRed:110/255.0 green:132/255.0 blue:238/255.0 alpha:1.0];
        rightButton.layer.cornerRadius = 10;
        [rightButton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightitem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        self.navigationItem.rightBarButtonItem = rightitem;
    }
    
    
    
    kWeakSelf(self);
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.arr[indexPath.row]];
    NSString *subjectType = dic[@"subjectType"];
    //单选 或 多选
    if ([subjectType isEqualToString:@"select"] || [subjectType isEqualToString:@"select_many"]) {
        RadioCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
        [cell.scrollView setContentOffset:CGPointMake(0,0) animated:NO];
        cell.numberLabel.text = [NSString stringWithFormat:@"%ld/%lu",(long)indexPath.row+1,(unsigned long)self.arr.count];
        cell.mianTextView.text = dic[@"questionnaireTopic"];
        if ([subjectType isEqualToString:@"select_many"]) {
            cell.mianTextView.text = [cell.mianTextView.text stringByAppendingString:@"（多选题）"];
        }
        [cell textViewDidChange:cell.mianTextView];
        cell.subjectType = subjectType;
        cell.topicIndex = [NSString stringWithFormat:@"%@",dic[@"topicIndex"]];
        cell.topTopicIndex = self.topTopicIndex;
        if (dic[@"data"]) {  //如果已经选中过了
            cell.seletedDic = dic[@"data"];
        }
        
        NSData *jsonData = [dic[@"topicOption"] dataUsingEncoding:NSUTF8StringEncoding];
        cell.topicOptionArr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        
        if (indexPath.row+1 == self.arr.count) {
            cell.lastValue = YES; //最后一个, 上一页时候做记录
        }
        
        //上一题
        cell.topBlcok = ^(NSDictionary * _Nonnull lastDic) {
            if (indexPath.row != 0) {
                kStrongSelf(self);
                
                int linkNum = (int)indexPath.row-1;
                
                for (int i=0; i<self.arr.count; i++) {
                    NSDictionary *tempDic = self.arr[i];
                    if ([self.topTopicIndex intValue] == [tempDic[@"topicIndex"] intValue]) {
                        linkNum = i;
                        self.topTopicIndex = self.arr[i][@"data"][@"topTopicIndex"];
                        break;
                    }
                }
                
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:linkNum inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
            }else{
                [GXToast showText:@"已经是第一题啦"];
            }
        };
        
        //下一题
        cell.nextBlcok = ^(NSDictionary * _Nonnull dataDic) {  //当前数据字典
            if (indexPath.row+1 < self.arr.count) {
                kStrongSelf(self);
                [dic setValue:dataDic forKey:@"data"];
                [self.arr replaceObjectAtIndex:indexPath.row withObject:dic];
                
                self.topTopicIndex = [NSString stringWithFormat:@"%@",dic[@"topicIndex"]];
                
                int linkNum = (int)indexPath.row+1;
                if ([dataDic[@"linkValue"] intValue] >= 0) {
                    for (int i=0; i<self.arr.count; i++) {
                        NSDictionary *tempDic = self.arr[i];
                        if ([dataDic[@"linkValue"] intValue] == [tempDic[@"topicIndex"] intValue]) {
                            linkNum = i;
                            break;
                        }
                    }
                }
                
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:linkNum inSection:0] atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
            }else{
                [GXToast showText:@"已经是最后一题啦"];
            }
        };
        
        //最后一题特殊处理
        cell.lastBlcok = ^(NSDictionary * _Nonnull lastDic) {
            if (indexPath.row+1 == self.arr.count) {
                [dic setValue:lastDic forKey:@"data"];
                [self.arr replaceObjectAtIndex:indexPath.row withObject:dic];
            }
        };
        
        if (indexPath.row+1 == self.arr.count) {
            cell.nextButton.hidden = YES;
            cell.topLeftGao.constant = self.view.frame.size.width/2-cell.topButton.frame.size.width/2;
        }else{
            cell.nextButton.hidden = NO;
            cell.topLeftGao.constant = 30;
        }
        
        if (indexPath.row == 0) {
            cell.topButton.hidden = YES;
            cell.nextRightGao.constant = self.view.frame.size.width/2-cell.nextButton.frame.size.width/2;
        }else{
            cell.topButton.hidden = NO;
            cell.nextRightGao.constant = 30;
        }
        
        return cell;
    }
    
    //填空
    else if ([subjectType isEqualToString:@"fill_blank"]) {
        BlankCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:blankCell forIndexPath:indexPath];
        cell.numberLabel.text = [NSString stringWithFormat:@"%ld/%lu",(long)indexPath.row+1,(unsigned long)self.arr.count];
        cell.mianTextView.text = dic[@"questionnaireTopic"];
        if (dic[@"data"]) {
            cell.textView.text = dic[@"data"][0][@"solutionId"];
        }else{
            cell.textView.text = @"";
        }
        cell.subjectType = subjectType;
        cell.topicIndex = [NSString stringWithFormat:@"%@",dic[@"topicIndex"]];
        cell.topTopicIndex = self.topTopicIndex;
        if (indexPath.row+1 == self.arr.count) {
            cell.lastValue = YES; //最后一个, 上一页时候做记录
        }
        
        cell.topBlcok = ^(NSDictionary * _Nonnull lastDic) {
            if (indexPath.row != 0) {
                kStrongSelf(self);
                
                int linkNum = (int)indexPath.row-1;
                for (int i=0; i<self.arr.count; i++) {
                    NSDictionary *tempDic = self.arr[i];
                    if ([self.topTopicIndex intValue] == [tempDic[@"topicIndex"] intValue]) {
                        linkNum = i;
                        self.topTopicIndex = self.arr[i][@"data"][@"topTopicIndex"];
                        break;
                    }
                }
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:linkNum inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
            }else{
                [GXToast showText:@"已经是第一题啦"];
            }
        };
        cell.nextBlcok = ^(NSDictionary * _Nonnull dataDic) {
            if (indexPath.row+1 < self.arr.count) {
                kStrongSelf(self);
                [dic setValue:dataDic forKey:@"data"];
                [self.arr replaceObjectAtIndex:indexPath.row withObject:dic];
                
                self.topTopicIndex = [NSString stringWithFormat:@"%@",dic[@"topicIndex"]];
                
                int linkNum = (int)indexPath.row+1;
                
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:linkNum inSection:0] atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
            }else{
                [GXToast showText:@"已经是最后一题啦"];
            }
        };
        
        //最后一题特殊处理
        cell.lastBlcok = ^(NSDictionary * _Nonnull lastDic) {
            if (indexPath.row+1 == self.arr.count) {
                [dic setValue:lastDic forKey:@"data"];
                [self.arr replaceObjectAtIndex:indexPath.row withObject:dic];
            }
        };
        
        if (indexPath.row+1 == self.arr.count) {
            cell.nextButton.hidden = YES;
            cell.topLeftGao.constant = self.view.frame.size.width/2-cell.topButton.frame.size.width/2;
        }else{
            cell.nextButton.hidden = NO;
            cell.topLeftGao.constant = 10;
        }
        
        if (indexPath.row == 0) {
            cell.topButton.hidden = YES;
            cell.nextRightGao.constant = self.view.frame.size.width/2-cell.nextButton.frame.size.width/2;
        }else{
            cell.topButton.hidden = NO;
            cell.nextRightGao.constant = 10;
        }
        
        return cell;
    }
    else{
        //错误情况处理
        RadioCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}


- (void)rightButtonClick:(UIButton *)button{
    NSDictionary *lastTopicDic = [self.arr lastObject][@"data"];
    if (!lastTopicDic) {
        [GXToast showText:@"请选择最后一题答案"];
        return;
    }
    
    
    button.enabled = NO;
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSMutableArray *dataArr = [NSMutableArray array];
    NSString *studentId = [[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"];
    NSString *time = [self nowTimeSwitchTimestamp];
    NSString *token = [[NSString stringWithFormat:@"%@-%@-%@-100001",studentId,self.questionnaireId,time] MD5];
    
    for (int i=0; i<self.arr.count; i++) {
        NSDictionary *tempDic = self.arr[i];
        if (tempDic[@"data"]) {
            
            NSString *str = tempDic[@"data"][@"topicIndex"];
            NSNumber *topicIndex = [NSNumber numberWithInt:[str intValue]];
            NSDictionary *dic = @{@"topicIndex":topicIndex,@"solutionId":tempDic[@"data"][@"solutionId"]};
            [dataArr addObject:dic];
        }
    }
    [dic setValue:dataArr forKey:@"data"];
    [dic setValue:self.questionnaireId forKey:@"questionnaireId"];
    [dic setValue:studentId forKey:@"studentId"];
    [dic setValue:time forKey:@"time"];
    [dic setValue:token forKey:@"token"];
    
    [ULNetHelper POST:insertQuestionnaireResultPath parameters:dic success:^(id responseObject) {
        button.enabled = YES;
        NSLog(@"交卷 = %@",responseObject);
        NSDictionary *dic = responseObject;
        long code = [dic[@"code"] longValue];
        if (code == 200) {
            FinishViewController *vc = [[FinishViewController alloc] init];
            vc.hidesBottomBarWhenPushed = YES;
            vc.title = self.title;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            NSString *msg = responseObject[@"msg"];
            [GXToast showText:msg];
        }
    } failure:^(NSError *error) {
        [GXToast showText:@"网络连接失败, 请优化网络后重新进入"];
        button.enabled = YES;
    }];
}


- (NSString *)nowTimeSwitchTimestamp{
    NSDate *datenow = [NSDate date];//现在时间
    //这里如果long不够用,就用(long long)
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];
    return timeSp;
}
@end
